package com.coocaa.optimizer;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by lu on 17-3-29.
 */

public class OptimizerApplication extends Application {
    public interface Config {
        void put(String key, String value);

        String get(String key);
    }

    public static abstract class ConfigFactory {
        public abstract Config create(Context context);

        private static class ConfigImpl implements Config {
            private SharedPreferences sp;

            ConfigImpl(Context context) {
                sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
            }

            @Override
            public void put(String key, String value) {
                try {
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString(key, value);
                    editor.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public String get(String key) {
                return sp.getString(key, "");
            }
        }


        public static final ConfigFactory factory = new ConfigFactory() {
            Config config = null;

            @Override
            public synchronized Config create(Context context) {
                if (config == null)
                    config = new ConfigImpl(context);
                return config;
            }
        };
    }

    @Override
    protected void attachBaseContext(Context base) {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                e.printStackTrace();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
        super.attachBaseContext(base);
    }

    public static void toast(final Context context, final String txt) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, txt, Toast.LENGTH_LONG).show();
                Log.d("Cleaner", txt);
            }
        };
        if (Looper.myLooper() != Looper.getMainLooper()) {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(r);
        } else
            r.run();
    }

    public static void toastDebug(Context context, String txt) {
        if (BuildConfig.DEBUG) {
            toast(context, txt);
        }
    }


    private static final String TAG = "CLEANER";

    public static void d(String s) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, s);
    }
}
